package com.liyunc.demo.bundle.file.manager.service;

import com.liyunc.demo.bundle.file.manager.config.AssetFileConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Component
public class BaseService {

    private static final String AUTO_BY_TIME = "auto_by_time_";
    private static final String AUTO_BY_NAME = "auto_by_name_";

    private static final long LEVEL_ONE_AMOUNT = 100L;

    @Autowired
    private AssetFileConfigProperties config;

    protected boolean checkSize(MultipartFile file) {
        if (Objects.isNull(file)) {
            return false;
        }
        return config.getDefaultLimitSize() >= file.getSize();
    }

    protected boolean checkSize(String content) {
        if (Objects.isNull(content)) {
            return false;
        }
        return config.getDefaultLimitSize() >= content.getBytes().length;
    }

    protected String getFilename() {
        return UUID.randomUUID().toString();
    }

    protected Path getAbsolutePath(Path relativePath) {
        if (Objects.isNull(relativePath)) {
            return getRelativePath("");
        }
        return Paths.get(config.getStorageRoot(), relativePath.toString());
    }

    protected Path getRelativePath(String filename) {
        return Paths.get(joinPathByStoreRule(filename), getFilename());
    }

    private String joinPathByStoreRule(String filename) {
        //目前创建文件夹规则就一种，根据日期创建
        if (config.getStorageRule().equalsIgnoreCase("time")) {
            return AUTO_BY_TIME + LocalDate.now();
        }
        if (config.getStorageRoot().equalsIgnoreCase("name")) {
            long hashCode = filename.hashCode();
            long parent = hashCode % LEVEL_ONE_AMOUNT;
            long child = hashCode / LEVEL_ONE_AMOUNT % (LEVEL_ONE_AMOUNT * LEVEL_ONE_AMOUNT);
            return AUTO_BY_NAME + parent + "/" + child;
        }
        return AUTO_BY_TIME + LocalDate.now();
    }
}
